package titt.service;

import titt.service.invoke.MethodParser;
import titt.service.proxy.server.ServerProxy;
import titt.service.os.ServiceObjectServer;
import titt.service.threading.MultipleTITTThreader;

public class BasicRegistrationStrategy implements RegistrationStrategy {

	private final ServiceMechanics sm;

	public BasicRegistrationStrategy(ServiceMechanics sm) {
		this.sm = sm;
	}

	public void unregister(Object o, boolean lazy) throws Exception {
		sm.unregister(o, lazy);
	}

	public void register(Object o, MethodParser parser, String... tokens) throws Exception {
		final ServiceObjectServer sos = sm.register(o, parser, tokens);
		MultipleTITTThreader.get().execute(new Runnable() {
			public void run() {
				try {
					while(invokeAndRepond(sos));	
				}
				catch(Exception e) {
					try {
						unregister(sos.getObject(), false);
					}
					catch(Exception e1) {}
				}
			}
		});
	}

	private boolean invokeAndRepond(ServiceObjectServer sos) throws Exception {

		ServicePackage pack = ServerProxy.get().withdraw(sos.getServiceID());

		if(pack == null) return false;

		MultipleTITTThreader.get().execute(sm.futureHandlePackage(sos, pack));

		return true;

	}
}
